﻿using UnityEngine;

namespace BToolkit
{
    [ExecuteInEditMode]
    public class CircleLayoutGroup : MonoBehaviour
    {
        public RectTransform cell;
        public int count = 6;
        public float radius = 100;
        public float offset = 90;

        private void Update()
        {
            if (count < 2)
            {
                count = 2;
            }
            if (radius < 0)
            {
                radius = 0;
            }
            if (!cell) return;
            if (transform.childCount < count)
            {
                for (int i = 0; i < count - 1; i++)
                {
                    RectTransform _cell = i == 0 ? cell : Instantiate(cell);
                    _cell.SetParent(cell.parent, false);
                    if (transform.childCount == count)
                    {
                        SetNames();
                        break;
                    }
                }
                SetNames();
            }
            else if (transform.childCount > count)
            {
                for (int i = 0; i < transform.childCount; i++)
                {
                    if (i >= count)
                    {
                        Transform trans = transform.GetChild(i);
                        if (trans) DestroyImmediate(trans.gameObject);
                    }
                }
            }

            float angle = offset;
            float subAngle = 360 / (float)count;
            for (int i = 0; i < transform.childCount; i++)
            {
                RectTransform cell = transform.GetChild(i) as RectTransform;
                Vector2 pos = cell.anchoredPosition;
                float radian = angle * Mathf.Deg2Rad;
                pos.x = Mathf.Cos(radian) * radius;
                pos.y = Mathf.Sin(radian) * radius;
                cell.anchoredPosition = pos;
                cell.localEulerAngles = new Vector3(0, 0, angle - 90);
                angle -= subAngle;
            }
        }

        void SetNames()
        {
            for (int i = 0; i < transform.childCount; i++)
            {
                transform.GetChild(i).name = "Cell_" + (i + 1);
            }
        }
    }
}